//
//  CMCometNetWorking.m
//  Commet
//
//  Created by tanqilong on 16/6/1.
//  Copyright © 2016年 tanqilong. All rights reserved.
//

#import "CMCometNetWorking.h"
#import <AFNetworking/AFNetworking.h>

@interface CMCometNetWorking ()
{
    NSTimeInterval _startNetTime; //发送请求时间
    NSTimeInterval _gotMessageTime; //收取信息时间
    BOOL _isConect;
}
@property (nonatomic,copy) void(^completeBlock)(id result); //成功后的回调
@property (nonatomic,copy) void(^errorBlock)(id error); //失败后的回调
@property (nonatomic,strong) AFURLSessionManager * sessionManager;
@property (nonatomic,strong) NSURLRequest * request;
@property (nonatomic,strong) NSURLSessionDataTask * dataTask;
@end

@implementation CMCometNetWorking

-(instancetype)init {
    self = [super init];
    if (self) {
        self.minInterval = 1;
    }
    return self;
}

+(CMCometNetWorking *)CometNetByUrl:(NSString *)urlStr paramDic:(NSDictionary *)paramDic complete:(void (^)(id result))complete Error:(void(^)(id error))error {
    CMCometNetWorking * netWorking = [CMCometNetWorking new];
    [netWorking CometNetByUrl:urlStr paramDic:paramDic complete:complete Error:error];
    [netWorking suspend];
    return netWorking;
}

+(CMCometNetWorking *)CometNetByUrl:(NSString *)url paramDic:(NSDictionary *)paramDic sessionConfiguration:(NSURLSessionConfiguration *)config complete:(void (^)(id))complete Error:(void (^)(id))error {
    CMCometNetWorking * netWorking = [CMCometNetWorking new];
    [netWorking CometNetByUrl:url paramDic:paramDic sessionConfiguration:config complete:complete Error:error];
    [netWorking suspend];
    return netWorking;
}

//开始访问
-(void)resume {
    if(_isConect) {
        return;
    }
    _isConect = YES;
    [self startComet];
}

//暂停访问
-(void)suspend {
    _isConect = NO;
}
//停止
-(void)cancel {
      _isConect = NO;
    [_dataTask cancel];
    _sessionManager = nil;
    _request = nil;
    _dataTask = nil;
}

-(void)CometNetByUrl:(NSString *)urlStr paramDic:(NSDictionary *)paramDic complete:(void (^)(id result))complete Error:(void(^)(id error))error {
    NSURLSessionConfiguration * config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    config.timeoutIntervalForRequest = 60;
    _sessionManager = [[AFURLSessionManager alloc]initWithSessionConfiguration:config];
    _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _request = [[AFHTTPRequestSerializer serializer]requestWithMethod:@"GET" URLString:urlStr parameters:paramDic error:nil];
    self.completeBlock = complete;
    self.errorBlock = error;
}

-(void)CometNetByUrl:(NSString *)urlStr paramDic:(NSDictionary *)paramDic sessionConfiguration:(NSURLSessionConfiguration *)config complete:(void (^)(id result))complete Error:(void(^)(id error))error {
    _sessionManager = [[AFURLSessionManager alloc]initWithSessionConfiguration:config];
    _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _request = [[AFHTTPRequestSerializer serializer]requestWithMethod:@"GET" URLString:urlStr parameters:paramDic error:nil];
    self.completeBlock = complete;
    self.errorBlock = error;
}

-(void)startComet{
    if (!_isConect) {
        return;
    }
    __weak typeof(self) ws = self;
    _dataTask = [_sessionManager dataTaskWithRequest:_request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            [ws errorNet:error httpResponse:(NSHTTPURLResponse *)response];
        }
        else {
            [ws successNet:responseObject];
        }
    }];
    _startNetTime = [[NSDate date] timeIntervalSince1970];
    [_dataTask resume];
}

//成功后的执行处理
-(void)successNet:(id)responseObject{
    id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    if (_completeBlock){
        if ([[result allKeys] count] == 1) {
            //30秒内为空发送的空字段
        } else {
            //非空字段执行语法块
            self.completeBlock(result);
        }
        
    }
    _gotMessageTime = [[NSDate date]timeIntervalSince1970];
    //执行遵循最小request间隔
    if (_gotMessageTime - _startNetTime < self.minInterval) {
        [self performSelector:@selector(startComet) withObject:nil afterDelay:(_minInterval - (_gotMessageTime - _startNetTime))];
        NSLog(@"%f秒后执行",_gotMessageTime - _startNetTime);
    } else {
        [self startComet];
    }
}

//错误后的处理
-(void)errorNet:(id)error httpResponse:(NSHTTPURLResponse *)response {
    if (_errorBlock) {
        self.errorBlock(error);
    }
    //超时重连
    if (response == nil) {
        [self performSelector:@selector(startComet) withObject:nil afterDelay:2];
        NSLog(@"超时重连...");
    }
    //断线重连
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        int errorCode = (int)response.statusCode / 100;
        if (errorCode == 5 || errorCode == 3 || errorCode == 1) {
            [self performSelector:@selector(startComet) withObject:nil afterDelay:2];
            NSLog(@"重连...");
        }
    }
}

-(void)dealloc {
    [self cancel];
    NSLog(@"释放");
}


@end
